<template>
	<div class="address">
		<!-- 顶部返回 -->
		<van-nav-bar
		  title="选择地址"
		  left-arrow
		  @click-left="$router.go(-1)"
		/>
		<!-- 内容部分 -->
		<van-address-list
		  v-model="chosenAddressId"
		  :list="list"
		  @add="onAdd"
		  @edit="onEdit"
		  @select="xuanze"
		/>
		
		
		<!-- 出口 -->
		<router-view></router-view>
	</div>
</template>

<script>
	import { Toast } from 'vant';
	import {reqAddressApi} from '@/api'
	import {mapState} from 'vuex'
	export default {
		name:'dizhi',
		data() {
		   return {
		     chosenAddressId: '1',
		     list: [],
		   }
		 },
		props:['address','id'],
		created() {
			// this.list = this.address
		},
		watch: {// 如果路由有变化，会再次执行该方法
			     "$route": "shujv",
				address:{
					immediate:true,
					handler(){
						this.list = this.address
					}
				},
				id:{
					immediate:true,
					handler(){
						this.chosenAddressId = this.id
					}
				}
			},
		computed:{
			...mapState(["isDenglu"]),
		},
		methods: {
			async shujv() {
				//请求已经服务器内部地址所有数据
				let {token} = this.isDenglu
				let ress = await reqAddressApi(token)
				if(ress.data.success_code === 200){
					this.list = ress.data.data.map(item=>{
						let {_id:id,address_name:name,address_phone:tel,address_area_detail:address,address_tag:isDefault} = item
						let data = {id,name,tel,address,isDefault}
						return data
					})
				}else{
					Toast('请求失败');
				}
			},
		    onAdd() {
		      this.$router.push({name:"newdizhi"})
		    },
		    onEdit(item, index) {
				this.$router.push({name:"edit",query:{id:item.id}})
		    },
			xuanze(item,index){
				this.$router.push({name:'confirm'})
				this.$emit('shujv',index)
			},
		},
	}
</script>

<style scoped lang="less">
	.address{
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 10;
		background-color: white;
	}
	.van-address-list{
		padding: 0;
	}
</style>